var express = require('express');
var router = express.Router();

const moment = require("moment");
const log = require('../../../core/logger').getLogger("system");
const helper = require('../../util/helper');
const menuService = require('../../services/admin/menuService');

module.exports = router;

var __toParams = function(parentMenu, menu){
    return {
        id: menu.menu_id,
        is: menu.menu_id + "_",
        parent_id: menu.parent_id,
        menu_name: menu.menu_name,
        parent_menu_name: parentMenu[menu.parent_id] || "无",
        menu_url: menu.menu_url,
        menu_icon: menu.menu_icon,
        created_at: menu.created_at?moment(menu.created_at).format("YYYY-MM-DD HH:mm:ss"):"",
        modified_at: menu.modified_at != "0000-00-00 00:00:00"?moment(menu.modified_at).format("YYYY-MM-DD HH:mm:ss"):"",
    }
};

/* GET home page. */
router.get('/', function(req, res) {
    res.render('admin/menu', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/menus'] || {},
        title: '菜单管理',
        router: '/menus'
    });
});

router.get('/load', async (req, res, next) => {
    var {search, start, length, draw} = req.query;
    if (!start || !length || !draw) {
        return res.status(401).json("invoke error!");
    }

    var keywords = search?search.value.trim():null;
    var start  = parseInt(start) || 0;
    var length = parseInt(length) || 0;
    var draw   = parseInt(draw) || 0;

    var menus = req.session.menus || [];
    var parentMenu = {};
    for (var i = 0; i < menus.length; i++) {
        var menu = menus[i];
        parentMenu[menu['menu_id']] = menu['menu_name'];
    }

    menuService.getMenus(keywords, start, length, function (err, data) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        var rows = [];
        data.rows.forEach(function (menu) {
            rows.push(__toParams(parentMenu,menu));
        });

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data: rows };
        return res.status(200).json(result);
    });
});

router.get('/getParentMenu', async (req, res, next) => {
    menuService.getParentMenu(function (err, result) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }
        res.status(200).json({error: 0, msg: "", data: result});
    });
});

router.get('/save', async (req, res, next) => {
    var user = req.session.user;
    log.info("save menu params: ", req.query);
    var menu_id = req.query.e_id;
    var menu_name = req.query.e_menu_name;
    var parent_id = req.query.e_parent_id;
    var menu_url = req.query.e_menu_url;
    var menu_icon = req.query.e_menu_icon;
    if (!menu_name || menu_name.trim() == "") {
        return res.status(200).json({error:1, msg:"菜单名不能为空!"});
    }

    if (menu_id) {
        const menuInfo = {
            menu_id: menu_id,
            menu_name: menu_name,
            parent_id: parent_id,
            menu_url: menu_url,
            menu_icon: menu_icon,
            modified_id: user.id,
            modified_at: new Date()
        };
        menuService.updateMenu(menuInfo, async function (err, result) {
            if (!!err) {
                return res.json({error:err.errCode, msg:err.message});
            }

            await helper.setMenus(req, user.id);
            await helper.saveOpLog(user.id, user.user_name, user.name, "更新菜单："+menu_name+";ID: "+menu_id);

            res.json({error: 0, msg: "菜单更新成功"});
        });
    } else {
        const menuInfo = {
            menu_name: menu_name,
            parent_id: parent_id,
            menu_url: menu_url,
            menu_icon: menu_icon,
            creator_id: user.id,
            created_at: new Date(),
            modified_id: user.id,
            modified_at: new Date()
        };
        menuService.createMenu(menuInfo, async function (err, result) {
            if (!!err) {
                return res.json({error:err.errCode, msg:err.message});
            }

            await helper.setMenus(req, user.id);
            await helper.saveOpLog(user.id, user.user_name, user.name, "新增菜单："+menu_name);

            return res.json({error: 0, msg: "新增菜单成功"});
        });
    }
});

router.delete('/delete', async (req, res, next) => {
    log.info("delete menu params: ", req.body);
    var ids = req.body.ids, user = req.session.user;
    if (!ids || ids.trim().length == 0) {
        res.status(200).json({error: 1, msg: '删除失败，必须选择一项'});
    }

    ids = ids.trim().split(",");
    menuService.destroyMenus(ids, async function (err, result) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        await helper.setMenus(req, user.id);
        await helper.saveOpLog(user.id, user.user_name, user.name, "删除菜单ID: "+ids, new Date());

        res.status(200).json({error: 0, msg: "用户删除成功"});
    });
});